﻿using System;
using System.Reflection;

namespace MyUi_WPF_Controls.DataGridCtr.Base
{
    public static class ReflectUtil
    {
        /// <summary>
        /// 获取属性的值。
        /// </summary>
        /// <param name="source"></param>
        /// <param name="propertyName"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="Exception"></exception>
        public static bool TryGetProperty<T>(this object source, string propertyName, out T result)
        {
            var type = source.GetType();
            var property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic);
            var value = property?.GetValue(source);
            if (value is T t)
            {
                result = t;
                return true;
            }

            result = default;
            return false;
        }
    }
}